package com.sky.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController("userDishController")
@RequestMapping("user/dish")
@Api(tags = "菜品相关接口")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 根据分类id查询菜品及口味
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品及口味")
    public Result<List<DishVO>> list(Long categoryId){
        log.info("根据分类id：{}查询菜品及口味",categoryId);
        //判断redis缓存里面有没有要查询的数据
        String key = "dish_" + categoryId;
        String string = (String) redisTemplate.opsForValue().get(key);
        List<DishVO> dishVOList = JSONObject.parseArray(string, DishVO.class);
        if (dishVOList != null && !dishVOList.isEmpty()){
            //如果说有则直接返回
            return Result.success(dishVOList);
        }
        //如果没有则访问数据库
        List<DishVO> dishes = dishService.getWithFlavorsOnSaleByCategoryId(categoryId);
        String jsonString = JSONObject.toJSONString(dishes);
        redisTemplate.opsForValue().set(key,jsonString);
        return Result.success(dishes);
    }
}
